<template>
  <div class="dialog">
    <el-dialog

        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :modal-append-to-body="false"
        :visible.sync="dialog.show">

      <el-upload
          v-loading="loading"
          element-loading-text="正在识别图片中..."
          element-loading-spinner="el-icon-loading"
          class="avatar-uploader"
          action="/api_2/api/updataImg"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
        <div class="upload-box">
          <img v-if="img_url" :src="img_url" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </div>
      </el-upload>

      <el-form :model="formData" :rules="rules" ref="formData">
        <el-form-item label="名字:" prop="name" :label-width="formLabelWidth">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email" :label-width="formLabelWidth">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
        <el-form-item label="旧密码:" prop="oldPassword" :label-width="formLabelWidth">
          <el-input v-model="formData.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassword" :label-width="formLabelWidth">
          <el-input v-model="formData.newPassword"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel()">取 消</el-button>
        <el-button type="primary" @click="onSubmit('formData')">提 交</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
  import jwt_decode from 'jwt-decode';
  import { editUser } from './../utils/api';
  export default {
    name: "EditUserDialog",
    props: {
      dialog: Object
    },
    data(){
      return {
        loading: false,
        formLabelWidth: '80px',
        img_url: '',
        formData: {
          name: '',
          email: '',
          oldPassword: '',
          newPassword: '',
          avatar: ''
        },
        rules: {
          name: [
            {
              required: true,
              message: '用户名不能为空',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 30,
              message: '长度在2到30个字符之间',
              trigger: 'blur'
            }
          ],
          email: [
            {
              type: 'email',
              required: true,
              message: '邮箱格式不正确',
              trigger: 'blur'
            }
          ],
          oldPassword: [
            {
              required: true,
              message: '旧密码不能为空',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 30,
              message: '长度在6到30字符之间',
              trigger: 'blur'
            }
          ],
          newPassword: [
            {
              required: true,
              message: '新密码不能为空',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 30,
              message: '长度在6到30字符之间',
              trigger: 'blur'
            }
          ]
        }
      }
    },
    computed: {
      user(){
        return this.$store.getters.user;
      }
    },
    methods: {
      initFormData(){
        this.formData.name = this.user.name;
        this.formData.id = this.user.id;
        this.formData.email = this.user.email;
        this.formData.avatar = '';
      },
      beforeAvatarUpload(file){
        this.loading = true;
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message ({
            message: "上传头像图片只能是 JPG 格式!",
            type: 'error'
          });
        }
        if (!isLt2M) {
          this.$message ({
            message: "上传头像图片大小不能超过 2MB!",
            type: 'error'
          });
        }
        return isJPG && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        let that = this;
        this.img_url = URL.createObjectURL(file.raw);
        let image = new Image();
        image.src = this.img_url;
        image.onload = function(){
          let base64 = that.getBase64Image(image);
          // console.log(base64);
          that.formData.avatar = base64;
          // console.log(that.formData.avatar);
          that.loading = false;
        }
      },
      getBase64Image(img) {
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        let ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
        let dataURL = canvas.toDataURL("image/"+ext);
        return dataURL;
      },
      onSubmit(formData){
        this.$refs[formData].validate(valid => {
          if(valid){
            if (this.img_url == ''){
              this.loading = true;
            }
            if (this.formData.avatar === ''){
              this.loading = true;
              this.$message ({
                  message: "图片正在上传中...",
                  type: 'success'
                });
            }else{
              editUser(this.formData.id, this.formData).then(data => {
              //修改成功
                this.$message ({
                  message: "修改成功",
                  type: 'success'
                });
                //更新vuex里的用户信息
                const userInfo = {};
                userInfo.id = data._id;
                userInfo.name = data.name;
                userInfo.email = data.email;
                userInfo.identity = data.identity;
                this.$store.dispatch("setUser", userInfo);
                const avatar = data.avatar;
                this.$store.dispatch("setAvatar", avatar);

                this.loading = false;
                //隐藏dialog
                this.dialog.show = false;

                this.formData.avatar = '';
            })
            .catch(err => console.log(err));
            }
            
          }
        });
      },
      onCancel(){
        this.dialog.show = false;
        this.loading = false;
        this.formData.avatar = '';
      },

      isEmpty(value) {
        return (
          value === undefined || value ===null ||
          (typeof value === "object" && Object.keys(value).length === 0) ||
          (typeof value === "string" && value.trim().length === 0)
        );
      }
    },
    created() {
      this.initFormData();  //初始化用户信息
    }
  }
</script>

<style scoped>
  .avatar-uploader{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
  }
  .upload-box {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-dialog__header {
     padding: 0;
  }
  .el-dialog__body {
    padding: 10px 20px 10px;
  }
  .dialog-footer{
    padding: 0 10px 10px;
  }
</style>